//
//  LSHandyJsonUtil.swift
//  LSTools
//
//  Created by Roffa Zhou on 2021/9/2.
//

/**
 LSHandyJsonUtil.modelToDict(model)!    //模型转字典
 LSHandyJsonUtil.jsonArrayToModels(result, IMIFeedbackMoreModel.self)  //json数组转model数组
 */

import UIKit
import HandyJSON

public typealias LSDictionary = [String: Any]


open class LSBaseModel:NSObject, HandyJSON {
    
    public required override init(){
        
    }
//    子类继承
    open func mapping(mapper: HelpingMapper) {
//            // 指定 id 字段用 "cat_id" 去解析
//            mapper.specify(property: &id, name: "cat_id")
//
//            // 指定 parent 字段用这个方法去解析
//            mapper.specify(property: &parent) { (rawString) -> (String, String) in
//                let parentNames = rawString.characters.split{$0 == "/"}.map(String.init)
//                return (parentNames[0], parentNames[1])
//            }
    }
   
}

public final class LSHandyJsonUtil: NSObject {
    
    /// json转model
    /// - Parameters:
    ///   - json: json对象  支持String/Dictionary
    ///   - modelType: 需要转换的对象类型
    /// - Returns: 转换后类型
    public static func jsonToModel<T>(_ json: T, _ modelType: HandyJSON.Type) -> HandyJSON?  {
        switch json {
        case let str as String:
            return modelType.deserialize(from: str)
        case let dict as LSDictionary:
            return modelType.deserialize(from: dict)
        default:
            lsPrint("格式不正确")
            return nil
        }
    }
    public static func jsonArrayToModels<T>(_ json: T,  _ modelType: HandyJSON.Type) -> [LSBaseModel?]?  {
        var arrayModel = [LSBaseModel]()
        switch json {
        case let str as String:
            let  array = try? str.dict() as? [LSDictionary]
            if array == nil {
                lsPrint("字符串转数组失败")
                return nil
            }
            for dict in array! {
                arrayModel.append(jsonToModel(dict, modelType) as! LSBaseModel)
            }
            return arrayModel
        case let array as [LSDictionary]:
            for dict in array {
                arrayModel.append(jsonToModel(dict, modelType)  as! LSBaseModel)
            }
            return arrayModel
        case let array as [String]:
            for str in array {
                arrayModel.append(jsonToModel(str, modelType)  as! LSBaseModel)
            }
            return arrayModel
        default:
            lsPrint("格式不正确")
            return nil
        }
    }
    public static func modelToJson(_ model: HandyJSON) -> String?{
        return model.toJSONString()
    }
    public static func modelToDict(_ model: HandyJSON) -> LSDictionary? {
        return model.toJSON()
    }
}
